//
//  PinLunViewController.m
//  OneWordNew
//
//  Created by qianfeng001 on 15-7-8.
//  Copyright (c) 2015年 朱共营. All rights reserved.
//

#import "PinLunViewController.h"
#import "PinLunModel.h"
#import "PinLunCell.h"
#import "AFNetworking.h"
#import "JHRefresh.h"
#import "LoginViewController.h"
#import "PLXQViewController.h"
@interface PinLunViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
{
    NSMutableArray *_dataArr;
    UITableView *_tableView;
    AFHTTPRequestOperationManager *_manager;
    
    BOOL _isRefrshing;
    BOOL _isLoadmoring;
    NSInteger _contun;
    UITextField *_myTF;
   
}
@property (nonatomic) UITextField *myTF;
@property (nonatomic) BOOL isRefrshing;
@property (nonatomic) BOOL isLoadmoring;
@property (nonatomic) NSInteger contun;;
@property(nonatomic,retain) NSMutableArray *dataArr;
@property(nonatomic,retain) UITableView *tableView;
@end

@implementation PinLunViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatUI];
    NSLog(@"%@",self.userId);
}
- (void)creatUI{
    self.automaticallyAdjustsScrollViewInsets=NO;
    self.dataArr=[[NSMutableArray alloc] init];
    self.tableView=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenSize.width, kScreenSize.height-64-49) style:UITableViewStylePlain];
    _manager=[AFHTTPRequestOperationManager manager];
    _manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    [self.tableView registerNib:[UINib nibWithNibName:@"PinLunCell" bundle:nil] forCellReuseIdentifier:@"PinLunCell"];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    [self.view addSubview:self.tableView];
    
    [self ctratRefrsh];
    [self creatPLBar];
    [self firstDown];
    
}
- (void)creatPLBar{
    UIView *imageView=[[UIView alloc] initWithFrame:CGRectMake(0, kScreenSize.height-64-49, kScreenSize.width, 49)];
   
   // UIImageView *myImage=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"input.png"]];
    imageView.tag=120;
   // myImage.frame=CGRectMake(0, 0, kScreenSize.width-90, 49);
     self.myTF=[[UITextField alloc] initWithFrame:CGRectMake(0, 5, kScreenSize.width-90, 40)];
   
    self.myTF.placeholder=@"我来说两句";
   // self.myTF.backgroundColor=[UIColor grayColor];
    self.myTF.delegate=self;
    [imageView addSubview:self.myTF];
    UIButton *button=[UIButton buttonWithType:UIButtonTypeSystem];
   
    [button setTitle:@"发表" forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"button.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    button.frame=CGRectMake(kScreenSize.width-90, 5, 90, 40);
    
    [imageView addSubview:button];
    imageView.backgroundColor=[UIColor grayColor];
  //  [imageView addSubview:myImage];
   // imageView.backgroundColor=[UIColor redColor];
    [self.view addSubview:imageView];

}
- (void)btnClick:(UIButton *)btn{
//    PLXQViewController *plxq=[[PLXQViewController alloc] init];
//    plxq.userId=self.userId;
//    plxq.token=self.token;
//    
//    [self.navigationController pushViewController:plxq animated:YES];
    
    
    
    [self senPL];
    [self.myTF resignFirstResponder];
   // [self oldPan];


}
- (void)senPL{
   
    NSString *usToken=[[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    
    __weak typeof(self)weakSelf=self;
   
    NSString *mytoken=[usToken stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
   
    NSLog(@"%@",mytoken);
    if (mytoken.length==2) {
        LoginViewController *login=[[LoginViewController alloc] init];
        
        [self.navigationController pushViewController:login animated:YES];
        return;
    }
    if (self.myTF.text.length==0) {
        [self showAliterWithTitle:@"提示" message:@"请输入内容"];
        return;
    }
    NSLog(@"%@",mytoken);
    NSLog(@"%@",self.myTF.text);
    NSLog(@"%@",self.userId);
    NSLog(@"%@",mytoken);
    NSDictionary *dict=@{@"token":mytoken,
                         @"content":self.myTF.text,
                         @"key":@"3a4b2a12539a916c040d069ae8ac8310",
                         @"ceshi_id":self.userId
                         };
    NSLog(@"%@",dict);
    NSString *url=[kSedPinLURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"%@",url);
    [_manager POST:url parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            if ([dict[@"code"] isEqual:@(0)]) {
                [weakSelf showAliterWithTitle:@"恭喜" message:@"发表成功"];
                weakSelf.myTF.text=@" ";
                
            }
        }
        else{
        
           [self showAliterWithTitle:@"提示" message:@"发表失败"];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"shibai");
        [self showAliterWithTitle:@"提示" message:@"检查网络"];
        
    }];
   
    
}
- (void)showAliterWithTitle:(NSString *)title message:(NSString *)message{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];

}
- (void)firstDown{
    _isRefrshing=NO;
    _isLoadmoring=NO;
    _contun=0;
    [self downLoadDataWithUrl:kPinLunUrl contun:_contun isRefresh:NO];
}
- (void)downLoadDataWithUrl:(NSString *)url contun:(NSInteger)contun isRefresh:(BOOL)isRefresh{
    __weak typeof(self)weakSelf=self;
    NSString *myUrl=[NSString stringWithFormat:url,self.userId.integerValue,_contun];
    NSLog(@"%@",myUrl);
    [_manager GET:myUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            if (_isRefrshing) {
                [weakSelf.dataArr removeAllObjects];
            }

            NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSArray *data=dict[@"data"];
            for (NSDictionary *subDict in data) {
                
                PinLunModel *model=[[PinLunModel alloc] init];
                NSDictionary *user=subDict[@"user"];
                model.avatar=user[@"avatar"];
                model.nickname=user[@"nickname"];
                model.created=subDict[@"created"];
                model.user_id=subDict[@"user_id"];
                model.content=subDict[@"content"];
                
                NSLog(@"%@",subDict[@"created"]);
                NSLog(@"%@",model.created);
                if ([subDict[@"user_id"]isEqual:@(1000095667)]||[subDict[@"user_id"]isEqual:@(1000099680)]||[subDict[@"user_id"]isEqual:@(1000104906)]||
                    [subDict[@"user_id"]isEqual:@(1000138235)]||
                    [subDict[@"user_id"]isEqual:@(1000135444)]||
                    [subDict[@"user_id"]isEqual:@(1000126456)]||
                    [subDict[@"user_id"]isEqual:@(1000134708)]) {
                    continue;
                    
                }
                
                [weakSelf.dataArr addObject:model];
            }
            [weakSelf.tableView reloadData];
            [weakSelf endRefresh];
            
            
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];

}
- (void)ctratRefrsh{
    __weak typeof(self)weakSerlf=self;
    [self.tableView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        if (weakSerlf.isRefrshing ) {
            return ;
        }
       weakSerlf.isRefrshing=YES;
       weakSerlf.contun=0;
        [weakSerlf downLoadDataWithUrl:kPinLunUrl contun:weakSerlf.contun isRefresh:YES ];
        
    }];
    [self.tableView addRefreshFooterViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        if (weakSerlf.isLoadmoring) {
            return ;
        }
        weakSerlf.isLoadmoring=YES;
        weakSerlf.contun+=10;
        [weakSerlf downLoadDataWithUrl:kPinLunUrl contun:weakSerlf.contun isRefresh:YES];
        
    }];

}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSLog(@"%ld",self.dataArr.count);
    return self.dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    PinLunCell *cell=[tableView dequeueReusableCellWithIdentifier:@"PinLunCell" forIndexPath:indexPath];
    PinLunModel *model=self.dataArr[indexPath.row];
 //   NSLog(@"ddddd%@",model.created);
    [cell shouDataWithModel:model];
    return cell;
}
- (void)endRefresh{
    if (_isRefrshing) {
        _isRefrshing=NO;
        [self.tableView headerEndRefreshingWithResult:JHRefreshResultSuccess];
    }
    if (_isLoadmoring) {
        _isLoadmoring=NO;
        [self.tableView footerEndRefreshing];
    }

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    //[self.myTF resignFirstResponder];
    [self oldPan];
    return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    PLXQViewController *plxq=[[PLXQViewController alloc] init];
    plxq.userId=self.userId;
    plxq.token=self.token;
    [self.navigationController pushViewController:plxq animated:YES];
    [self.myTF resignFirstResponder];
    
    
//    UIView *myview=(UIView *)[self.view viewWithTag:120];
//    myview.tag=110;
//    [UIView beginAnimations:nil context:NULL];
//    [UIView setAnimationDuration:0.25];
//    myview.frame=CGRectMake(0, kScreenSize.height-360, kScreenSize.width, 49);
//    
//    [UIView commitAnimations];


}
- (void)oldPan{
    [self.myTF resignFirstResponder];
    UIView *myview=(UIView *)[self.view viewWithTag:110];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.25];
    
    myview.frame=CGRectMake(0, kScreenSize.height-64-49, kScreenSize.width, 49);
    [UIView commitAnimations];

}

- (void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden=YES;
     [self.tableView reloadData ];

}

@end
